import React, { PureComponent, Fragment } from 'react';
import {
  Form,
  Input,
  Select,
  Modal,
  Button,
  Drawer,
  Radio, Icon, Upload, DatePicker,
} from 'antd';
import { connect } from 'dva';

import Editer from '../../../../src/common/Editor.js';

const FormItem = Form.Item;
const RadioGroup = Radio.Group;


@connect(({ global }) => ({
  global,
}))
@Form.create()
class UpdateForm extends PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      imgList: [],
      editorValue: '',
    };
    this.formLayout = {
      labelCol: { span: 7 },
      wrapperCol: { span: 13 },
    };
  }



  handleChange = (info) => {
    info = info.map((file) => {
      if (file.response) {
        file.url = file.response.url;
      }
      return file;
    });
    info = info.filter((file) => {
      if (file.response) {
        return file.response.status === 'success';
      }
      return true;
    });
    this.setState({ imgList: info });
  };

  CustomRequest = (componentsData) => {
    let _this = this;
    const { dispatch, form } = this.props;
    let originFile = componentsData.file;
    const formData = new FormData();
    formData.append('multipartFile', originFile);
    formData.append('name', originFile.name);
    formData.append('uid', originFile.uid);
    dispatch({
      type: 'global/upload',
      payload: formData,
      callback(res) {
        if (res.code === 200) {
          let obj = {
            ...res.msg,
          };
          form.setFieldsValue({
            img: res.msg.url,
          });
          _this.handleChange([obj]);
        }
      },
    });
  };

  // 表单
  renderContent = () => {
    const { form, values } = this.props;
    const { imgList, editorValue } = this.state;
    const iconProps = {
      action: `/img/upload`,
      showUploadList: { showPreviewIcon: true, showRemoveIcon: false },
      multiple: false,
      customRequest: this.CustomRequest,
      listType: 'picture-card',
      className: 'upload-list-inline',
    };
    return [
      <FormItem key="title" {...this.formLayout} label="标题">
        {form.getFieldDecorator('title', {
          rules: [{ required: true, message: '请输入标题！' }],
          initialValue: values.title,
        })(<Input placeholder="请输入标题"/>)}
      </FormItem>,
      <FormItem key="subTitle" {...this.formLayout} label="副标题">
        {form.getFieldDecorator('subTitle', {
          rules: [{ required: true, message: '请输入副标题！' }],
          initialValue: values.subTitle,
        })(<Input placeholder="请输入副标题"/>)}
      </FormItem>,
      <FormItem key="bannerImg" {...this.formLayout} label="图片">
        {
          imgList.length > 0 ?
            form.getFieldDecorator('img', {
              rules: [{ required: form.getFieldValue('platform') !== '2', message: '请上传图片！' }],
              initialValue: values.img,
            })(
              <Upload {...iconProps} fileList={imgList}>
                <Icon type="upload"/> 上传
              </Upload>,
            ) : form.getFieldDecorator('img', {
              rules: [{ required: true, message: '请上传图片！' }],
              initialValue: values.img,
            })(
            <Upload {...iconProps} fileList={
              values.img ? [{
                name: values.img,
                uid: 1,
                url: values.img,
              }] : []
            }>
              <Icon type="upload"/> 上传
            </Upload>,
            )}
      </FormItem>,
      <FormItem key="status" {...this.formLayout} label="状态">
        {form.getFieldDecorator('status', {
          rules: [{ required: true, message: '请选择状态！' }],
          initialValue: values.status || 1,
        })(
          <RadioGroup>
            <Radio value={1}>启用</Radio>
            <Radio value={2}>停用</Radio>
          </RadioGroup>,
        )}
      </FormItem>,
      <FormItem key="platform" {...this.formLayout} label="平台">
        {form.getFieldDecorator('platform', {
          rules: [{ required: true, message: '请选择发布平台！' }],
          initialValue: values.platform,
        })(
          <Select style={{ width: '100%' }}>
            <Select.Option value={1}>app</Select.Option>
            <Select.Option value={2}>pc</Select.Option>
            <Select.Option value={3}>全部</Select.Option>
          </Select>,
        )}
      </FormItem>,
      <FormItem key="context" label="内容">
        {form.getFieldDecorator('context', {
          rules: [{ required: true, message: '请选填写文章内容！' }],
          initialValue: editorValue,
        })(
          <Editer context={values.context}/>,
        )}

      </FormItem>,
    ];
  };
  // editerSubmit = (text) => { //
  //   const { dispatch } = this.props;
  //   this.props.form.setFieldsValue({
  //     context: `Hiale' ? 'man' : 'lady'}!`,
  //   });
  // };

  //弹窗
  render() {
    const { updateModalVisible, handleModalVisible, modalVisible, form, values, handleUpdate, handleAdd } = this.props;
    //完成
    const handleNext = () => {
      form.setFieldsValue({
        context: localStorage.getItem('editerInfo'),
      });
      form.validateFields((err, fieldsValue) => {
        const formVals = { ...values, ...fieldsValue };
        if (err) return;
        if (!updateModalVisible) {
          handleAdd(formVals);
          form.resetFields();
        } else {
          handleUpdate(formVals);
          form.resetFields();
        }
      });
    };
    const darwerVisible = () => {
      form.resetFields();
      handleModalVisible(false, [])
    };
    return (
      <Drawer
        title={!updateModalVisible ? '新增文章' : '修改文章'}
        width={720}
        destroyOnClose
        visible={modalVisible}
        closable={false}
        onClose={() => darwerVisible()}
        style={{
          overflow: 'auto',
          height: 'calc(100% - 108px)',
        }}>
        {this.renderContent()}
        <div style={{
            position: 'absolute',
            left: 0,
            bottom: 0,
            width: '100%',
            borderTop: '1px solid #e9e9e9',
            padding: '10px 16px',
            background: '#fff',
            textAlign: 'right',
          }}>
          <Button onClick={() => handleModalVisible(false, [])} style={{ marginRight: 8 }}>
            取消
          </Button>
          <Button onClick={handleNext} type="primary">
            提交
          </Button>
        </div>
      </Drawer>
    );
  }
}

export default UpdateForm;
